#include "snowboy/snowboy-detect-c-wrapper.h"
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "record.h"

#define SILENCE_THRESHOLD 5 // 5秒的静音

int main()
{
    // 创建snowboy检测器
    SnowboyDetect* detector = SnowboyDetectConstructor("common.res", "laotie.pmdl");
    if (!detector)
    {
        return EXIT_FAILURE;
    }

    // 获取检测器支持的音频数据参数
    int bits = SnowboyDetectBitsPerSample(detector);
    int channels = SnowboyDetectNumChannels(detector);
    int rate = SnowboyDetectSampleRate(detector);

    printf("采样深度: %d\n", bits);
    printf("声道数量: %d\n", channels);
    printf("采样频率: %d\n", rate);

    // 打开音频采集设备
    snd_pcm_uframes_t period = 999;
    snd_pcm_t* capture = record_open("hw:0,0", SND_PCM_FORMAT_S16_LE, channels, rate, &period);
    if (!capture)
    {
        return EXIT_FAILURE;
    }

    char* buffer = malloc(snd_pcm_frames_to_bytes(capture, period)); // 分配缓冲区
    if (!buffer) {
        perror("malloc");
        record_close(capture);
        SnowboyDetectDestructor(detector);
        return EXIT_FAILURE;
    }

    int recording = 0; // 录音状态变量
    time_t silence_start = 0; // 静音开始时间变量
    FILE *pcm_file = NULL; // PCM文件指针

    while (1)
    {
        snd_pcm_sframes_t frames = snd_pcm_readi(capture, buffer, period); // 从PCM设备读取数据
        if (frames < 0)
        {
            fprintf(stderr, "Error from read: %s\n", snd_strerror(frames));
            snd_pcm_recover(capture, frames, 0);
            continue;
        }

        int status = SnowboyDetectRunDetection(detector, (int16_t*)buffer, snd_pcm_frames_to_bytes(capture, frames) / sizeof(int16_t), 0);

        if (status > 0)
        {
            printf("检测到唤醒词\n");
            if (!recording)
            {
                printf("开始录音\n");
                pcm_file = start_recording("output.pcm");
                if (!pcm_file)
                {
                    free(buffer);
                    record_close(capture);
                    SnowboyDetectDestructor(detector);
                    return EXIT_FAILURE;
                }
                recording = 1;
                silence_start = 0; // 重置静音时间
            }
        }
        else if (status == -2 && recording)
        {
            if (silence_start == 0)
            {
                silence_start = time(NULL); // 记录静音开始时间
            }
            else if (difftime(time(NULL), silence_start) >= SILENCE_THRESHOLD)
            {
                printf("检测到连续5秒的静音，停止录音\n");
                stop_recording(pcm_file);
                recording = 0;
                silence_start = 0;
            }
        }
        else
        {
            silence_start = 0; // 重置静音时间
        }

        if (recording && pcm_file)
        {
            fwrite(buffer, snd_pcm_frames_to_bytes(capture, frames), 1, pcm_file); // 将录音数据写入文件
        }
    }

    free(buffer);
    record_close(capture);
    SnowboyDetectDestructor(detector);

    return EXIT_SUCCESS;
}
